package com.zha.boss.client.mail;

import jakarta.annotation.Resource;
import jakarta.mail.internet.MimeMessage;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @Author: zha
 * @CreateTime: 2024年09月17日 21:23
 * 邮件的客户端,发送邮件
 */
@Component
public class MailClient {
    @Resource
    private JavaMailSender javaMailSender;
    // 没有附件的邮件,简单邮件
    public boolean sendSimpleMail(MailProperties mailProperties) {
        boolean isSend =false;
        try {
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            simpleMailMessage.setFrom(mailProperties.getFrom());   // 发送者
            simpleMailMessage.setTo(mailProperties.getTo());    // 接收者
            simpleMailMessage.setSentDate(new Date()); // 邮件发送日期
            simpleMailMessage.setSubject(mailProperties.getSubject()); // 邮件标题
            simpleMailMessage.setText(mailProperties.getText()); // 邮件正文
            // 发送这个邮件
            javaMailSender.send(simpleMailMessage);
            isSend = true;
        } catch (Exception e) {
            isSend = false;
            e.printStackTrace();
        }
        return isSend;
    }
    // 有附件的邮件
    public boolean sendAttachmentsMail(MailProperties mailProperties) {
        boolean isSend =false;
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            // 构建邮件
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(mailProperties.getFrom());   // 发送者
            helper.setTo(mailProperties.getTo());    // 接收者
            helper.setSentDate(new Date()); // 邮件发送日期
            helper.setSubject(mailProperties.getSubject()); // 邮件标题
            helper.setText(mailProperties.getText()); // 邮件正文
            // 附件
            List<Attachment> attachments = mailProperties.getAttachments();
            if (attachments!= null && attachments.size() > 0){
                for (Attachment attachment : attachments) {
                    helper.addAttachment(attachment.getName(), attachment.getFile());
                }
            }
            // 发送这个邮件
            javaMailSender.send(helper.getMimeMessage());
            isSend = true;
        } catch (Exception e) {
            isSend = false;
            e.printStackTrace();
        }
        return isSend;
    }
}
